package xyz.icxl.android.architecture.data.net.okhttp.interceptors


import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 文件描述：公共参数
 *
 * 文件创建人：ChenXinLei
 *
 * 文件创建人联系方式：502616659(QQ)
 *
 * 创建时间：2020 年 04月 27 日
 *
 * 文件版本：v1.0
 *
 * 版本描述：创建文件
 */
class PublicParameterInterceptor(private val getParameter:()->HashMap<String,String>) : Interceptor{
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val publicUrl =request.url.newBuilder().build()
        request = request.newBuilder().url(publicUrl).build()
        if (request.method == "GET") {
            //如果是get请求
            val url = request.url
            val newUrl = url.newBuilder().apply {
                getParameter().forEach {entry ->
                    addEncodedQueryParameter(entry.key,entry.value)
                }
            }
            request = request.newBuilder()
                .url(newUrl.build()).build()
            return chain.proceed(request)

        }else {
            // 构造新的请求表单
            val builder = FormBody.Builder(java.nio.charset.StandardCharsets.UTF_8)
            val body = request.body
            if (body is FormBody ){
                //将以前的参数添加
                for (i in 0 until body.size) {
                    builder.addEncoded(body.encodedName(i), body.encodedValue(i))
                }
            }
            //追加新的参数
            getParameter().forEach {entry ->
                builder.addEncoded(entry.key,entry.value)
            }
            request = request.newBuilder().post(builder.build()).build()//构造新的请求体
        }
        return chain.proceed(request)
    }

}